class MessagesController < ApplicationController
  before_filter :login_required, :set_nav_session
  before_filter :unread_messages_amount, :only => [:index, :outbox, :new, :show, :reply]
  
  # Inbox
  def index
    @messages = Message.paginate(:all, :page => params[:page] || 1,
                                 :conditions => "receiver_id=#{current_user.id}",
                                 :order => "created_at desc")
  end
  
  # Outbox
  def outbox
    @messages = Message.paginate(:all, :page => params[:page] || 1,
                                 :conditions => "sender_id=#{current_user.id}",
                                 :order => "created_at desc")
  end
  
  def new
    @message = Message.new
    @message.receiver = User.find(params[:to].to_i)
    #@message.receiver_id = @receiver.id
  end
  
  def create
    @message = Message.new(params[:message])
    user = User.find(@message.receiver_id)
    @message.sender_id = current_user.id
    @message.save!
    flash[:notice] = "你写的消息已经发送给#{user.login}"
    redirect_back_or_default(user_url(user))
  end
  
  def show
    @message = Message.find(params[:id])
    ownership_check(@message, current_user)
    if @message.receiver_id == current_user.id # when user check inbox
      @status = "inbox"
    elsif @message.sender_id == current_user.id # when user check outbox
      @status = "outbox"
    end
    if @message.receiver_id == current_user.id
      @message.update_attributes!(:unread => false) if @message.unread?
    end
  end
  
  # GET /messages/:id;reply
  def reply
    @original = Message.find(params[:id])
    ownership_check(@original, current_user)
    @message = Message.new
    @message.receiver_id = @original.sender_id
    @message.sender_id   = @original.receiver_id
    @message.title       = "Re:" + @original.title
    @message.content     = "\r\n\r\n\r\n\r\n#{@original.sender.login}说：\r\n| #{@original.content.gsub("\r\n", "\r\n| ")}"
  end
  
  def destroy
    @message = Message.find(params[:id])
    @message.destroy
    flash[:notice] = "你刚刚删除了一条站内消息"
    redirect_back_or_default(messages_url)
  end
  
  def destroy_all
    0.upto(Message.per_page-1) do |i|
      id = params[:messages]["no_#{i}"].to_i
      if id != 0
        msg = Message.find(id)
        msg.destroy
      end
    end
    redirect_back_or_default(messages_url)
  end
  
  private
  def ownership_check(message, user)
    unless message.own_by?(current_user)
      flash[:notice] = "你不能查看别人的消息"
      redirect_to messages_url
    end
  end
  
  def set_nav_session
    session[:nav] = ""
  end
end
